package com.qx.cn.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qx.cn.model.Role;
import com.qx.cn.model.RoleMenu;
import com.qx.cn.model.UserRole;
import com.qx.cn.service.RoleGroupMappingService;
import com.qx.cn.service.RoleMenuService;
import com.qx.cn.service.RoleService;
import com.qx.cn.service.UserRoleService;
import com.qx.cn.tool.ReDupList;
import com.qx.cn.vo.RoleVO;

@Controller
@RequestMapping("/role")
public class RoleController
{
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Autowired
    private RoleMenuService roleMenuService;
    
    @Autowired
    private RoleGroupMappingService roleGroupMappingService;
    
    @ResponseBody
    @RequestMapping(value = "/queryRoleListByPage")
    public JSONObject queryRoleListByPage(int page, int rows)
    {
        List results = roleService.queryRolesByPage(page, rows);
        JSONArray arrJson = new JSONArray();
        if (!results.isEmpty())
        {
            for (int i = 0; i < results.size(); i++)
            {
                Object[] row = (Object[])results.get(i);
                JSONObject json = new JSONObject();
                json.put("roleId", (Integer)row[0]);
                json.put("roleName", (String)row[1]);
                json.put("enabled", (Integer)row[2]);
                json.put("roleDesc", (String)row[3]);
                String optMenuUrl = "<span style='color:#00C;cursor:hand;' onclick=giveRoleToMenu('" + (Integer)row[0] + "','【" + (String)row[1] + "】')>[设置菜单]</span>&nbsp;";
                json.put("optRoleUrl", optMenuUrl);
                arrJson.add(json);
            }
        }
        JSONObject object = new JSONObject();
        List<Role> roles = roleService.queryAllRoles();
        object.put("total", roles.size());
        object.put("rows", arrJson);
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "/saveRole")
    public JSONObject saveRole(Long roleId, String roleName, String roleDesc, Integer enabled, String strBuffer, String userId, String orgCode)
        throws IOException
    {
        if (roleId != null)
        {
            Role reRole = roleService.loadRoleById(roleId);
            reRole.setRoleName(roleName);
            reRole.setEnabled(enabled);
            reRole.setRoleDesc(roleDesc);
            roleService.saveRole(reRole);
        }
        else
        {
            Role role = new Role();
            role.setRoleName(roleName);
            role.setEnabled(enabled);
            role.setRoleDesc(roleDesc);
            roleService.saveRole(role);
        }
        JSONObject object = new JSONObject();
        object.put("result", 1);
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "/deleteRole")
    public JSONObject deleteRole(Long roleId)
    {
        String roleIdStr = String.valueOf(roleId);
        boolean flag1 = roleGroupMappingService.deleteRoleAtMapping(roleIdStr);
        boolean flag2 = userRoleService.deleteUserRoles(roleIdStr);
        boolean flag3 = roleMenuService.deleteRoleMenusById(roleIdStr);
        boolean flag = roleService.deleteRole(roleId);
        JSONObject object = new JSONObject();
        if ((flag) && (flag1) && (flag2) && (flag3))
        {
            object.put("result", 1);
            object.put("errorMsg", "删除角色成功");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "删除角色失败");
        }
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "/loadRoleById")
    public JSONObject loadRoleById(Long roleId)
    {
        JSONObject object = new JSONObject();
        Role role = roleService.loadRoleById(roleId);
        object.put("roleId", role.getRoleId());
        object.put("roleName", role.getRoleName());
        object.put("enabled", role.getEnabled());
        object.put("roleDesc", role.getRoleDesc());
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "/saveUserToRole")
    public JSONObject saveUserToRole(Long roleId, String orgCode, String strBuffer)
    {
        boolean flag = true;
        JSONObject object = new JSONObject();
        String[] userId = strBuffer.split(",");
        String roleIdStr = String.valueOf(roleId);
        List<UserRole> userRoles = userRoleService.queryUserRolesById(orgCode, roleIdStr);
        if (userRoles.size() > 0)
        {
            if (userRoleService.deleteUserRoles(orgCode, roleIdStr))
            {
                for (int i = 0; i < userId.length; i++)
                {
                    UserRole userRole = new UserRole();
                    userRole.setRoleId(roleId);
                    userRole.setUserId(Long.valueOf(userId[i]));
                    userRole.setOrgCode(orgCode);
                    boolean flag1 = userRoleService.saveUserRole(userRole);
                    if (!flag1)
                    {
                        flag = false;
                    }
                }
            }
        }
        else
        {
            for (int i = 0; i < userId.length; i++)
            {
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(Long.valueOf(userId[i]));
                userRole.setOrgCode(orgCode);
                boolean flag1 = userRoleService.saveUserRole(userRole);
                if (!flag1)
                {
                    flag = false;
                }
            }
        }
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "设置角色成功!");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "设置角色失败!");
        }
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "/saveMenuToRole")
    public JSONObject saveMenuToRole(Long roleId, String strBuffer)
    {
        boolean flag = true;
        JSONObject object = new JSONObject();
        String[] menuCode = strBuffer.split(",");
        String roleIdStr = String.valueOf(roleId);
        List<RoleMenu> roleMenus = roleMenuService.queryRoleMenusById(roleIdStr);
        List<String> menuList;
        if (roleMenus.size() > 0)
        {
            List<RoleMenu> rms = roleMenuService.queryRoleMenusByIdAndBT(roleIdStr);
            boolean flag2 = roleMenuService.deleteRoleMenusById(roleIdStr);
            if (flag2)
            {
                List list = new ArrayList();
                for (int i = 0; i < menuCode.length; i++)
                {
                    list.add(menuCode[i]);
                    if (menuCode[i].length() != 4)
                    {
                        list.add(menuCode[i].substring(0, menuCode[i].length() - 3));
                    }
                }
                menuList = ReDupList.removeDuplicate(list);
                boolean flag1 = true;
                for (String mls : menuList)
                {
                    boolean addFlag = false;
                    String addMenuCode = "";
                    if (rms.size() > 0)
                    {
                        for (RoleMenu rm : rms)
                        {
                            if (mls.equals(rm.getMenuId()))
                            {
                                RoleMenu roleMenu = new RoleMenu();
                                roleMenu.setRoleId(roleIdStr);
                                roleMenu.setMenuId(mls);
                                addMenuCode = rm.getMenuId();
                                if ((rm.getButtonIds() != null) && (rm.getTabIds() == null))
                                {
                                    roleMenu.setButtonIds(rm.getButtonIds());
                                }
                                else if ((rm.getButtonIds() == null) && (rm.getTabIds() != null))
                                {
                                    roleMenu.setTabIds(rm.getTabIds());
                                }
                                else if ((rm.getButtonIds() != null) && (rm.getTabIds() != null))
                                {
                                    roleMenu.setTabIds(rm.getTabIds());
                                    roleMenu.setButtonIds(rm.getButtonIds());
                                }
                                flag1 = roleMenuService.saveRoleMenu(roleMenu);
                                if (!flag1)
                                {
                                    flag = false;
                                }
                            }
                            else
                            {
                                addFlag = true;
                            }
                        }
                        if ((addFlag) && (!addMenuCode.equals(mls)))
                        {
                            RoleMenu roleMenu = new RoleMenu();
                            roleMenu.setRoleId(roleIdStr);
                            roleMenu.setMenuId(mls);
                            flag1 = roleMenuService.saveRoleMenu(roleMenu);
                            if (!flag1)
                            {
                                flag = false;
                            }
                        }
                    }
                    else
                    {
                        RoleMenu roleMenu = new RoleMenu();
                        roleMenu.setRoleId(roleIdStr);
                        roleMenu.setMenuId(mls);
                        boolean flag3 = roleMenuService.saveRoleMenu(roleMenu);
                        if (!flag3)
                        {
                            flag = false;
                        }
                    }
                }
            }
        }
        else
        {
            List list = new ArrayList();
            for (int i = 0; i < menuCode.length; i++)
            {
                list.add(menuCode[i]);
                if (menuCode[i].length() != 4)
                {
                    list.add(menuCode[i].substring(0, menuCode[i].length() - 3));
                }
            }
            menuList = ReDupList.removeDuplicate(list);
            for (String mls : menuList)
            {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleIdStr);
                roleMenu.setMenuId(mls);
                boolean flag1 = roleMenuService.saveRoleMenu(roleMenu);
                if (!flag1)
                {
                    flag = false;
                }
            }
        }
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "设置角色菜单成功!");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "设置角色菜单失败!");
        }
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "/queryAllRolesToUser")
    public JSONObject queryAllRolesToUser(Long userId)
    {
        List<Role> roles = roleService.queryAllRoles();
        List<UserRole> userRoles = userRoleService.queryRolesByUserId(userId);
        List roleVOs = new ArrayList();
        for (Role role : roles)
        {
            int sign = 0;
            RoleVO roleVO = new RoleVO();
            for (UserRole ur : userRoles)
            {
                if (role.getRoleId().equals(ur.getRoleId()))
                {
                    sign = 1;
                }
            }
            roleVO.setRoleId(role.getRoleId());
            roleVO.setRoleName(role.getRoleName());
            roleVO.setRoleDesc(role.getRoleDesc());
            roleVO.setEnabled(role.getEnabled());
            roleVO.setSign(Integer.valueOf(sign));
            roleVOs.add(roleVO);
        }
        JSONObject object = new JSONObject();
        object.put("datas", roleVOs);
        object.put("result", 1);
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "/saveTabsMenuToRole")
    public JSONObject saveTabsMenuToRole(Long roleId, String strBuffer)
    {
        JSONObject object = new JSONObject();
        String roleIdStr = String.valueOf(roleId);
        roleMenuService.updateRoleTabsByRoleId(roleIdStr);
        if (!"".equals(strBuffer))
        {
            String[] menuTabs = strBuffer.split("#");
            List list = new ArrayList();
            for (int i = 0; i < menuTabs.length; i++)
            {
                String[] mbs = menuTabs[i].split(",");
                list.add(mbs[0]);
            }
            List<String> list2 = ReDupList.removeDuplicate(list);
            for (String ls : list2)
            {
                StringBuffer sBuffer = new StringBuffer();
                for (int i = 0; i < menuTabs.length; i++)
                {
                    String[] mbs = menuTabs[i].split(",");
                    if (mbs[0].equals(ls))
                    {
                        sBuffer.append(mbs[1]).append(",");
                    }
                }
                roleMenuService.updateRoleTabsByMenuCode(roleIdStr, ls, sBuffer.toString());
            }
        }
        object.put("result", 1);
        object.put("errorMsg", "设置角色选项卡成功!");
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "/saveButsMenuToRole")
    public JSONObject saveButsMenuToRole(Long roleId, String strBuffer)
    {
        JSONObject object = new JSONObject();
        String roleIdStr = String.valueOf(roleId);
        roleMenuService.updateRoleButsByRoleId(roleIdStr);
        if (!"".equals(strBuffer))
        {
            String[] menuButs = strBuffer.split("#");
            List list = new ArrayList();
            for (int i = 0; i < menuButs.length; i++)
            {
                String[] mbs = menuButs[i].split(",");
                list.add(mbs[0]);
            }
            List<String> list2 = ReDupList.removeDuplicate(list);
            for (String ls : list2)
            {
                StringBuffer sBuffer = new StringBuffer();
                for (int i = 0; i < menuButs.length; i++)
                {
                    String[] mbs = menuButs[i].split(",");
                    if (mbs[0].equals(ls))
                    {
                        sBuffer.append(mbs[1]).append(",");
                    }
                }
                roleMenuService.updateRoleButsByMenuCode(roleIdStr, ls, sBuffer.toString());
            }
        }
        object.put("result", 1);
        object.put("errorMsg", "设置角色按钮成功!");
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "/saveRoleToUser")
    public JSONObject saveRoleToUser(String strBuffer, String userId, String orgCode)
    {
        boolean flag = true;
        JSONObject object = new JSONObject();
        String[] roleId = strBuffer.split(",");
        List userRoles = userRoleService.queryRolesByUserId(Long.valueOf(userId));
        if (userRoles.size() > 0)
        {
            boolean flag2 = userRoleService.deleteRolesUser(Long.valueOf(userId));
            if (flag2)
            {
                for (int i = 0; i < roleId.length; i++)
                {
                    UserRole userRole = new UserRole();
                    userRole.setRoleId(Long.valueOf(roleId[i]));
                    userRole.setUserId(Long.valueOf(userId));
                    userRole.setOrgCode(orgCode);
                    boolean flag1 = userRoleService.saveUserRole(userRole);
                    if (!flag1)
                    {
                        flag = false;
                    }
                }
            }
        }
        else
        {
            for (int i = 0; i < roleId.length; i++)
            {
                UserRole userRole = new UserRole();
                userRole.setRoleId(Long.valueOf(roleId[i]));
                userRole.setUserId(Long.valueOf(userId));
                userRole.setOrgCode(orgCode);
                boolean flag1 = userRoleService.saveUserRole(userRole);
                if (!flag1)
                {
                    flag = false;
                }
            }
        }
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "设置角色成功!");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "设置角色失败!");
        }
        return object;
    }
}